package cn.wolfcode.luowowo.controller;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.exception.LogicException;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("users")
public class UserController {
    /**
     * 配置属性是在website-api中,使用的位置userInfoserviceImpl如果放在userInfoserviceImpl类
     * mgrsite项目启动时会报错
     * mgrsite项目没有这三个属性,所以我们放在website-api项目中
     */
    @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.sign}")
    private String smsSign;
    @Value("${sms.appkey}")
    private String smsAppkey;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @GetMapping("get")
    public Object get(String id){
        return userInfoService.get(id);
    }
    @GetMapping("checkPhone")
    public Object checkPhone(String phone){
        boolean ret = userInfoService.checkPhone(phone);
        return !ret;
    }
    @GetMapping("sendVerifyCode")
    public Object sendVerifyCode(String phone){
        userInfoService.sendVerifyCode(phone,smsUrl,smsAppkey,smsSign);
        return JsonResult.success();
    }
    @RequireLogin
    @GetMapping("getCurrentUser")
    public Object getCurrentUser(HttpServletRequest request){
        String token = request.getHeader("token");
        UserInfo userInfo = userInfoRedisService.getUserByToken(token);
        return JsonResult.success(userInfo);
    }
    @PostMapping("regist")
    public Object regist(String phone,String nickname,String password,String rpassword,String verifyCode){
        userInfoService.regist(phone,nickname,password,rpassword,verifyCode);
        return JsonResult.success();
    }
    @PostMapping("login")
    public Object login(String username,String password){
        //登录
        UserInfo user = userInfoService.login(username,password);
        //将用户缓存到redis中
        String token = userInfoRedisService.setToken(user);
        //页面需要token user
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",user);
        return JsonResult.success(map);
    }
}
